package com.nio;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * BIO 每个链接对应每个线程
 */
public class SocketBIO {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(9090,20);
        System.out.println("step1: new ServerSocket(9090)");

        while (true){
            Socket client = server.accept(); //阻塞
            System.out.println("step2: client\t"+client.getPort());

            new Thread(new Runnable() {
                @Override
                public void run() {
                    InputStream in = null;
                    try {
                        in = client.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                        while (true){
                            String dataline = reader.readLine(); //阻塞
                            if (dataline!=null){
                                System.out.println(dataline);
                            }else {
                                client.close();
                                break;
                            }
                        }
                        System.out.println("客户打断断开链接");
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
